﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using Data.implement;
using LYPrice.Models;
using Services.Implement;
using Services.Interface;

namespace LYPrice.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        private static readonly log4net.ILog log =
            log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        public ActionResult Index()
        {
            return View();
        }
        public static string VerifyLogin(Info userInfo)
        {
            var isNotTel = !Regex.IsMatch(userInfo.PhoneNum ?? string.Empty.Trim(), @"^[1][3-5,8]\d{9}$");
            if (isNotTel)
                return "~/Result/ErrorInfo";

            var isNotName = string.IsNullOrEmpty(userInfo.Name ?? string.Empty.Trim());
            if (isNotName)
                return "~/Result/ErrorInfo";

            var isNotProvince = string.IsNullOrEmpty(userInfo.Province ?? string.Empty.Trim());
            if (isNotProvince)
                return "~/Result/ErrorInfo";

            var isNotCity = string.IsNullOrEmpty(userInfo.City ?? string.Empty.Trim());
            if (isNotCity)
                return "~/Result/ErrorInfo";

            var isNotAddress = string.IsNullOrEmpty(userInfo.Address ?? string.Empty.Trim());
            if (isNotAddress)
                return "~/Result/ErrorInfo";
            

            return string.Empty;

        }
        public ActionResult Log(Info userInfo)
        {

            var result=VerifyLogin(userInfo);
            if (!string.IsNullOrEmpty(result))
            {
                return Redirect(result);
            }
            Session["priceInfo"] = userInfo;
            string appid = ConfigurationSettings.AppSettings["appid"];
            string url = ConfigurationSettings.AppSettings["url"];
            return Redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + url + "/GetWeiXinInfo/" + "&response_type=code&scope=snsapi_userinfo&state=log#wechat_redirect");
        }

        public ActionResult GetWeiXinInfo(string code, string state)
        {
            var info = Session["priceInfo"] as Info;
            Session.Clear();
            if (info==null)
            {
                return Redirect("~/Result/ErrorInfo");
            }
            try
            {
                log.Info("Init service.");
                IWeixinAuthService service = new WeixinAuthService();
                IPriceRecordService priceRecordService=new PriceRecordService();
                string token = string.Empty;
                string openId = string.Empty;
                string errorCode = string.Empty;
                string errorMsg = string.Empty;
                log.Info("Start Get Token.");
                if (service.GetToken(code, out token, out openId, out errorCode, out errorMsg))
                {
                    log.Info("Get the token " + token + " openId " + openId + " error:" + errorCode + errorMsg);
                    if (!string.IsNullOrEmpty(errorCode))
                        return Redirect("~/Result/Exception");
                    if (!ValidOpenId(openId))
                    {
                        log.Info("not in the list:"+openId);
                        return Redirect("~/Result/NotInList");
                    }
                    log.Info("Start Get User");
                    WeiXinUser userInfo = service.GetUser(token, openId, out errorMsg, out errorCode);

                    if (userInfo == null)
                    {
                        log.ErrorFormat("get userInfo fail, errorCode:{0}, errorMsg:{1}", errorCode, errorMsg + " OpenId:" + openId);
                        return Redirect("~/Result/CantGetInfoFromWeixin");
                    }
                    log.Info("user is " + User.ToString());

                    var flag=priceRecordService.SaveRecords(info.Province + info.City + info.Address, info.PhoneNum, info.Name,
                        userInfo);

                    if (flag)
                    {
                        return Redirect("~/Result/Successful");
                    }
                    else
                    {
                        return Redirect("~/Result/HaveLog");
                    }



                }
                else
                {
                    return Redirect("~/Result/ErrorInfo");

                }
            }
            catch (Exception e)
            {
                log.Error("there is an error in GetWeiXinInfo: "+e);
                return Redirect("~/Result/Exception");
            }

            
        }


        private bool ValidOpenId(string openId)
        {
            var temp = ConfigurationManager.AppSettings["openidList"] as string;
            string[] list = temp.Split(',');

            foreach (var s in list)
            {
                if (s==openId)
                {
                    return true;
                }

            }
            return false;
        }
    }
}
